package com.tsystems.tuni.sportplanet.dao;

import java.util.List;

import javax.persistence.Query;

import com.tsystems.tuni.sportplanet.entity.Player;
import com.tsystems.tuni.sportplanet.entity.Result;
import com.tsystems.tuni.sportplanet.entity.Season;
import com.tsystems.tuni.sportplanet.entity.Sport;
import com.tsystems.tuni.sportplanet.entity.Team;

/**
 * 
 * @author Yuriy Eremin
 * 
 */
public class TeamDAOImpl extends GenericDAOImpl<Team> implements TeamDAO {

	public TeamDAOImpl() {
		super();
	}

	@SuppressWarnings("unchecked")
	public List<Player> getAllPlayers(Team team) {
		return (List<Player>) team.getPlayers();
	}

	@SuppressWarnings("unchecked")
	public List<Team> getTeamsBySport(Sport sport) {
		Query query = em
				.createQuery("select t from Team as t where t.sport=:sport");
		query.setParameter("sport", sport);
		return query.getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Team> getAllTeamsFromCity(String city, Sport sport) {
		String q = "select t from Team t where t.sport=:sport and t.company in (select distinct d.company from Department d where d.location.city=:city)";
		Query query = em.createQuery(q);
		query.setParameter("city", city);
		query.setParameter("sport", sport);
		return query.getResultList();
	}

	@Override
	public int getLastTeamScore(Team team) {
		String q = "select r from Result r where r.team=:team and r.game.time = (select max(time) as max from Game g)";
		Query query = em.createQuery(q);
		query.setParameter("team", team);
		Result result = (Result) query.getSingleResult();
		return result.getScore();
	}

	@SuppressWarnings("unchecked")
	@Override
	public int getTeamScoreFromSeason(Team team, Season season) {
		String q = "select r from Result r where r.game.season=:season and r.team=:team";
		Query query = em.createQuery(q);
		query.setParameter("team", team);
		query.setParameter("season", season);
		List<Result> resultList = query.getResultList();
		int result = 0;
		for (Result r : resultList) {
			result += r.getScore();
		}
		return result;
	}

}
